import axios from 'axios';

const api = axios.create({
  baseURL: window.location.origin,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 10000
});

// instance.interceptors.response.use((reply) => reply.data);

// 格式化请求地址;
function renderUrlTemplate(method, url, params) {
  if (method === 'get') {
    const tmp = url.replace(/{([^}]+)}/g, (m, p) => {
      const ret = params[p];
      delete params[p];
      return ret;
    });
    return `/api${tmp}`;
  }
  return `/api${url}`;
}

// get请求
export function get(url, options) {
  const newUrl = renderUrlTemplate('get', url, options);
  return api({ url: newUrl, method: 'get', params: options });
}

// post请求
export function post(url, options) {
  const newUrl = renderUrlTemplate('post', url, options);
  return api({ url: newUrl, method: 'post', data: options });
}
